﻿using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using TrinityAPI.Base.Models;

namespace TrinityAPI.Base.Tools
{
    public static class JSONParameterHelper
    {
        public static string GetNecessaryJsonObjectStringValue(this Newtonsoft.Json.Linq.JObject jobject, string key, string parentPath = "")
        {
            string value = jobject.GetJsonObjectStringValue(key);
            if (string.IsNullOrWhiteSpace(value))
                throw new ConfigException("{0}{1} is null or empty", string.IsNullOrWhiteSpace(parentPath) ? "" : parentPath + ".", key);
            return value;
        }

        public static JToken GetNecessaryJsonObjectValue(this Newtonsoft.Json.Linq.JObject jobject, string key, string parentPath = "")
        {
            var value = jobject.GetJsonObjectValue(key);
            if (value == null)
                throw new ConfigException("{0}{1} is null", string.IsNullOrWhiteSpace(parentPath) ? "" : parentPath + ".", key);
            return value;
        }

        public static JObject GetNecessaryJsonObject(this Newtonsoft.Json.Linq.JObject jobject, string key, string parentPath = "")
        {
            var value = jobject.GetJsonObject(key);
            if (value == null)
                throw new ConfigException("{0}{1} is null or not an object", string.IsNullOrWhiteSpace(parentPath) ? "" : parentPath + ".", key);
            return value;
        }

        public static List<JObject> GetNecessaryJsonObjectList(this Newtonsoft.Json.Linq.JObject jobject, string key, string parentPath = "")
        {
            var value = jobject.GetJsonObjectList(key);
            if (value == null || value.Count == 0)
                throw new ConfigException("{0}{1} is null or an empty array", string.IsNullOrWhiteSpace(parentPath) ? "" : parentPath + ".", key);
            return value;
        }

        public static List<T> GetNecessaryJsonObjectList<T>(this Newtonsoft.Json.Linq.JObject jobject, string key, string parentPath = "")
        {
            var value = jobject.GetJsonObjectList<T>(key);
            if (value == null || value.Count == 0)
                throw new ConfigException("{0}{1} is null or an empty array", string.IsNullOrWhiteSpace(parentPath) ? "" : parentPath + ".", key);
            return value;
        }
    }
}